﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Threading.Tasks;
using WebMatrix.WebData;
using LynxWiki.Filters;
using LynxWiki.Models;

namespace LynxWiki.Controllers
{
    [InitializeSimpleMembership]
    [Authorize(Roles = "WikiAdmin")]
    public class UserRolesController : Controller
    {
        //
        // GET: /UserRoles/

        [TopicActionFilter]
        public async Task<ActionResult> Index()
        {
            AllUsersAndRoles userData = new AllUsersAndRoles();
            HttpClient client = ClientUtility.GetMembershipClient();
            try {
                HttpResponseMessage response = await client.GetAsync("api/UserProfile");
                response.EnsureSuccessStatusCode();

                IEnumerable<UserProfile> users = await response.Content.ReadAsAsync<IEnumerable<UserProfile>>();
                userData.Users = users.ToList<UserProfile>();
            }
            catch (SerializationException ex) {
                Debug.Print(ex.Message);
            }
            catch (HttpRequestException ex) {
                Debug.Print(ex.Message);
            }

            userData.AppRoles = Roles.GetAllRoles().OfType<string>().ToList();
            return View(userData);
        }

        [HttpPost]
        [TopicActionFilter]
        public ActionResult ListUserRoles(FormCollection fc)
        {
            UserRoles uRoles = new UserRoles();
            uRoles.AppRoles = Roles.GetRolesForUser(fc["UserName"]).OfType<string>().ToList();
            uRoles.User = fc["UserName"];
            return View(uRoles);
        }
        [HttpPost]
        [TopicActionFilter]
        public ActionResult ListUserMissingRoles(FormCollection fc)
        {
            UserRoles uRoles = new UserRoles();
            uRoles.AppRoles = Roles.GetAllRoles().OfType<string>().Except(Roles.GetRolesForUser(fc["UserName"]).AsEnumerable<string>()).ToList();
            uRoles.User = fc["UserName"];
            return View(uRoles);
        }

        [HttpPost]
        public ActionResult AddRoleToUser(FormCollection fc)
        {
            Roles.AddUserToRole(fc["UserName"], fc["Role"]);

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult RemoveRoleFromUser(FormCollection fc)
        {
            Roles.RemoveUserFromRole(fc["UserName"], fc["Role"]);

            return RedirectToAction("Index");
        }

        [HttpPost]
        public async Task<ActionResult> DeleteUser(FormCollection fc)
        {
            string[] roles = Roles.GetRolesForUser(fc["UserName"]);
            Roles.RemoveUserFromRoles(fc["UserName"], roles);

            HttpClient client = ClientUtility.GetMembershipClient();
            try {
                HttpResponseMessage response = await client.DeleteAsync("api/UserProfile" + fc["UserId"]);
                response.EnsureSuccessStatusCode();

            }
            catch (SerializationException ex) {
                Debug.Print(ex.Message);
            }
            catch (HttpRequestException ex) {
                Debug.Print(ex.Message);
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult AddRole(FormCollection fc)
        {
            Roles.CreateRole(fc["newRole"]);

            return RedirectToAction("Index");
        }

        [HttpPost]
        [TopicActionFilter]
        public ActionResult ListUsersInRole(FormCollection fc)
        {
            RoleUsers rUsers = new RoleUsers();
            rUsers.AppUsers = Roles.GetUsersInRole(fc["Role"]).OfType<string>().ToList();
            rUsers.AppRole = fc["Role"];
            return View(rUsers);
        }

        [HttpPost]
        public ActionResult RemoveRole(FormCollection fc)
        {
            string[] users = Roles.GetUsersInRole(fc["Role"]);
            if (users.Length > 0) {
                Roles.RemoveUsersFromRole(users, fc["Role"]);
            }
            Roles.DeleteRole(fc["Role"]);

            return RedirectToAction("Index");
        }



    }
}
